package site.ruyi.devclient.core;

import java.io.IOException;
import java.io.OutputStream;

import org.apache.log4j.Layout;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.WriterAppender;

import javafx.scene.control.TextArea;

/**
 * 用于输出日志到TextArea的appender
 * @author self
 *
 */
public class TextAreaAppender extends WriterAppender {

	private static final String LAYOUT_PATTERN = "%-d{yyyy-MM-dd HH:mm:ss} [%p] (%c) -> %m%n";
	
	public TextAreaAppender(TextArea textArea) {
		this(textArea,new PatternLayout(LAYOUT_PATTERN));
	}
	
	public TextAreaAppender(TextArea textArea,Layout layout) {
		this.setLayout(layout);
		this.setWriter(createWriter(new TextAreaStream(textArea)));
	}
	
    private static class TextAreaStream extends OutputStream {
        private TextArea textArea;
    	
    	public TextAreaStream(TextArea textArea) {
    		this.textArea = textArea;
    	}

        public void close() {}

        public void flush() {}

        public void write(final byte[] b) throws IOException {
        	final String message = new String(b);
        	this.textArea.appendText(message);
        }

        public void write(final byte[] b, final int off, final int len)
            throws IOException {
        	final String message = new String(b,off,len);
        	this.textArea.appendText(message);
        }

        public void write(final int b) throws IOException {
        	char[] chars=new char[] {(char) b};
        	final String message = new String(chars);
        	this.textArea.appendText(message);
        }
    }
}
